const ALY = require('aliyun-sdk');
const fs = require('fs')

module.exports = {
    init(conf){
        this.config = conf
        this.ossRelativePath = conf.relativePath
        this.fullPath = conf.fullPath
        this.ossStream = require('aliyun-oss-upload-stream')(new ALY.OSS(conf));
    },

    upload :function(file,key){
        let self = this;
        return new Promise(function(resultcb,errcb){

            let upload = self.ossStream.upload({
                Bucket: self.config.Bucket,
                Key: self.ossRelativePath+key
            });
            let startTime = Date.now()
            upload.on('part',function(part){
                // console.log('func part:',part)
            })

            upload.on('error',function(err){
                errcb(err);
            })

            upload.on('uploaded',function(details){
                console.log('self ==', self);
                let s = (Date.now()-startTime);
                resultcb(self.fullPath+self.ossRelativePath+key)
                // console.log('details:',s);
            })
            try{
                let read = fs.createReadStream(file);
                read.pipe(upload);
            }catch(e){
                errcb(e);
            }
        })
    }
}
